package com.hangim.pce.controller;

import com.hangim.pce.model.BaseElement;
import com.hangim.pce.model.vo.request.ElementVo;
import com.hangim.pce.service.BaseElementService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.Query;
import com.github.pig.common.util.R;
import com.github.pig.common.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 药品表 前端控制器
 * </p>
 *
 * @author hongjiliang
 * @since 2018-10-19
 */
@RestController
@RequestMapping("/baseElement")
public class BaseElementController extends BaseController {
    @Autowired
    private BaseElementService baseElementService;

    /**
     * 通过ID查询
     *
     * @param id ID
     * @return BaseElement
     */
    @GetMapping("/{id}")
    public R<BaseElement> get(@PathVariable Long id) {
        return new R<>(baseElementService.selectById(id));
    }


    /**
     * 分页查询信息
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @RequestMapping("/page")
    public Page page(@RequestParam Map<String, Object> params) {
        params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        return baseElementService.selectPage(new Query<>(params), new EntityWrapper<BaseElement>().like("name", (String) params.get("name")));
    }

    /**
     * 添加
     *
     * @param baseElement 实体
     * @return success/false
     */
    @PostMapping
    public R<Integer> add(@RequestBody BaseElement baseElement) {
        return new R<>(baseElementService.insert(baseElement));
    }

    /**
     * 删除
     *
     * @param id ID
     * @return success/false
     */
    @DeleteMapping("/{id}")
    public R<Integer> delete(@PathVariable Long id) {
        BaseElement baseElement = new BaseElement();
        baseElement.setId(id);
        baseElement.setUpdatedAt(new Date());
        baseElement.setActive(0);
        return new R<>(baseElementService.updateById(baseElement));
    }

    /**
     * 编辑
     *
     * @param baseElement 实体
     * @return success/false
     */
    @PutMapping
    public R<Integer> edit(@RequestBody BaseElement baseElement) {
        baseElement.setUpdatedAt(new Date());
        return new R<>(baseElementService.updateById(baseElement));
    }


    /**
     * 成分规则
     *
     * @param id 实体
     * @return ElementVo
     */
    @GetMapping("rule/{id}")
    public R<ElementVo> getRules(@PathVariable Long id) {
        return new R<>(baseElementService.getRules(id));
    }

    /**
     * 成分规则
     *
     * @param elementVo 实体
     * @return success/false
     */
    @ResponseBody
    @PostMapping("/saveRules")
    public R<Boolean> saveRules(@RequestBody ElementVo elementVo) {
        return new R<>(baseElementService.saveRules(elementVo));
    }
}
